<template>
  <div class="flex flex-col min-w-[800px] h-[400px]">
    <div class="flex-grow w-full h-full overflow-hidden">
      <div class="absolute top-0 z-10 p-2 flex flex-wrap justify-center">
        <el-button text icon="zoom-in" @click="onZoomIn">
        </el-button>
        <el-button text icon="zoom-out" @click="onZoomOut">
        </el-button>
        <el-button text icon="full-screen" @click="onZoomFill">
        </el-button>
      </div>
      <svg :id="id" class="w-full h-full color-primary"/>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {Transformer} from 'markmap-lib';
import {Markmap} from 'markmap-view';

const props = defineProps<{
  text: string;
  id: string;
}>();

let instance: Markmap | null = null;

onMounted(() => {
  const el = document.getElementById(props.id) as any;
  instance = Markmap.create(el);

  const transformer = new Transformer();
  const {root} = transformer.transform(props.text);
  instance?.setData(root);
  instance?.fit();
});

watch(
    () => props.text,
    (val) => {
      const transformer = new Transformer();
      const { root } = transformer.transform(val);
      instance?.setData(root);
      instance?.fit();
    }
);

function onZoomIn() {
  instance?.rescale(2);
}

function onZoomOut() {
  instance?.rescale(0.5);
}

function onZoomFill() {
  instance?.fit();
}
</script>
